<?php

	function FilterCookie($str){
   		return checksqlstr($str);
	}

	function reloadLogin()
	{
		/*去掉 asp 自动登陆，有安全原因 各平台可以去reloadLogin函数，然后上线 by Wangsl 2011-7-5 */
		return;
	}
	
	function clearcookie($mc){
		if (isset($_COOKIE["usercheck"])){
			$user_check = $_COOKIE["usercheck"];
			$mc->delete("userid".$user_check);
			$mc->delete("username".$user_check);
			$mc->delete("usertype".$user_check);
			$mc->delete("LoginFrom".$user_check);
			$mc->delete("500wan_username".$user_check);
		}
		setcookie("500wan_username","",null,"/",getdomain());
		setcookie("500wan_userps","",null,"/",getdomain());
		setcookie("500wan%5Fusername","",null,"/",getdomain());
		setcookie("500wan%5Fuserps","",null,"/",getdomain());
		setcookie("usercheck","",null,"/",getdomain());
		// 最后登录时间和IP
		setcookie("500wan_lastIP", getIP(), time() + 60 * 60 * 24, '/', getdomain());
		setcookie("500wan_lastTime", date('Y-m-d H:i:s'), time() + 60 * 60 * 24, '/', getdomain());		
	}	
	
	function GetUserInfoFromCookie($DirectUrl){
		$sql_str=new oci_str();
		if ($_SESSION["username"]!=""){
			  $_COOKIE["500wan_username"]=base64_encode($_SESSION["username"]);
			  //'============以下判断用户的密码是否写入：如果用户没有密码保存
			  if (strlen(base64_decode($_COOKIE["500wan_userps"]))<1){
			  		$sqlarr=array(
			  			'fields'    => "UI_Lock,UI_TmpPass,UI_UserType,ui_username",
						'table'     => "b_userinfo",  
						'condition' => " UI_UserName='".$_SESSION["username"]."'",
			  		);
			  		$result=$sql_str->oci_sql_select($sqlarr,$dbh);
			  		if ($result) $_COOKIE['500wan_userps'] = $result[0][1];
			  }
		}ElseIf (base64_decode($_COOKIE["500wan_username"])>""){
			  $tmpusername=FilterCookie(base64_decode($_COOKIE["500wan_username"]));
			  if ($tmpusername!=""){
				  //'=====重新session
				  $sqlarr=array(
			  			'fields'    => "UI_Lock,UI_TmpPass,UI_UserType,ui_username",
						'table'     => "b_userinfo",  
						'condition' => " UI_UserName='".$_SESSION["username"]."'",
			  	  );
				  $result=$sql_str->oci_sql_select($sqlarr,$dbh);
				  if ($result){
				  	if ($result[0][1]==base64_decode($_COOKIE['500wan_userps'])){
				  		//'=======判断本地保存密码是否与相同
				  		$_SESSION['username']=$tmpusername;
				  		$_SESSION['usertype']=$result[0][2];
				  		$_SESSION['pwdt']="";
				  		$_SESSION['LoginFrom']="IndexLogin";	// 登陆成功后直接进入合买区 
				  	}else{
				  		$_COOKIE['500wan_userps']="";
				  		$_COOKIE['500wan_username']="";
				  		if ($DirectUrl!="") header("location:/pages/trade/main.php");
				  	}
				  }else{
				  		$_COOKIE['500wan_userps']="";
				  		$_COOKIE['500wan_username']="";
						if ($DirectUrl!="") header("location:/pages/trade/main.php");
				  }		
				  	
			  }
		}
	}
/*
sub Jmail(email,subject,mailbody)
    '发送邮件
    'email 邮箱地址，subject 邮件主题，mailbody 邮件内容
    '调用示例： call jmail() 
	on error resume next	
	Dim JMail,SendMail,contentId
	set JMail= Server.CreateObject("JMAIL.Message")
	jmail.silent = true    '屏蔽例外错误，返回FALSE跟TRUE两值j
    jmail.logging = false   '启用邮件日志
    jmail.Charset = "GB2312"     '邮件的文字编码为国标
	JMail.ContentType = "text/html"
	JMail.MailServerUserName="master@500wan.cn"
	jmail.MailServerPassword = "QWERTYUIOP"
	JMail.from="master@500wan.cn"
	JMail.Subject=Subject			
	JMail.Body= mailbody
	jmail.AddRecipient email	 '发送邮件	
	JMail.Priority=3
	jmail.Send("61.145.118.222:25")
	jmail.close
	set JMail = nothing		
end sub
*/
	function checkuserstr($str){
	   	//检测用户注册名
	   	$result="";
		if (strlen($str)== 0 || is_null($str)){
			$result = "";
			return $result;
		}
		//$strfilter="/\$|\(|\)|\*|\+|\-|\.|\[|]|\?|\\|\^|\{|\||}|~|`|!|@|#|%|&|_|=|<|>|/|,|'| |　|\:|林美眉|林MM|林美湄|大鳄浮头|500158|今夜很冷|余超群|小赌怡情|小??怡情|乾坤|易讯|卓越|天下为安/";
		//$strfilter="/\$|\(|\)|\*|\+|\-|\.|\[|]|\?|\\|\^|\{|\||}|\~|\`|\!|\@|\#|\%|\&|\_|\=|\<|\>|\/|\,|\'| |　|\:|林美眉|林MM|林美湄|大鳄浮头|500158|今夜很冷|余超群|小赌怡情|小??怡情|乾坤|易讯|卓越|天下为安/i";
		$strfilter='/\$|\(|\)|\*|\+|\-|\.|\[|\]|\?|\\|\^|\{|\||\}|\~|\`|\!|\@|\#|\%|\&|\_|\=|\<|\>|\/|\,|\'|\ |\　|\:|林美眉|林MM|林美湄|大鳄浮头|500158|今夜很冷|余超群|小赌怡情|小??怡情|乾坤|易讯|卓越|天下为安/i';
		
		$toustr="/^ddn.*?$|^QQ_.*?$|客服/";  //检查开头字符
		
		if (!preg_match($strfilter,$str)){
			$regex_pattern="/法[ 　]*轮[ 　]*功|台独|台湾独立|藏独|西藏独立|地震预测/";
			$result=preg_replace($regex_pattern,"",$str);
		}else {
			$result = "";
		}
		
		if (preg_match($strfilter, $str)) $result = "";
		
        $strfilter1 = '/^(\x00\w|[\x4e-\x9e][\x00-\xff]|\x9f[\x00-\xa5])+$/'; //输入的数据必须是中文、英文和数字
		
		if (!preg_match($strfilter1,iconv('gb18030', 'ucs-2be', $str)))$result = "";
		
		return $result;
	}
	function checkflg($str){
	    //检测用户输入的内容，先过滤法轮功
	    $regex_pattern="/法[ 　]*轮[ 　]*功|台独|台湾独立|藏独|西藏独立|地震预测/";
	    $result=preg_replace($regex_pattern,"",$str);
	    return $result;
	}

	function checkint($str,$def){
	   //检测输入的是否是整数
	   //str 输入的字符串，def如果str非法则返回的整数
	   $result="";
	   $str = strval(trim($str));
	   if (strlen($str)== 0 || is_null($str)){
	   		$result=$def;
	   		return $result;
	   }
	   
	   if (is_numeric($str))$result=intval($str);
	   else $result=$def;
	   
	   return $result;
	}

	function checknumber($str,$def){
		$result="";
		if (strlen($str)== 0 || is_null($str)){
	       $result = $def;
	       return $result;
		}
	   if (is_numeric($str)){
	       $result=$str;
	   }else{
	       $result=$def;
	   }
	   return $result;
	}
	
	function checkexpect($lotid,$str){
		$patterns=array();
		$patterns[0]="/^[0-9]{5}$/";
		$patterns[9]="/^[0-9]{6}$/";
		$patterns[29]="/^[0-9]{8}[0-9]{2}$/";
		$patterns[12]="/^[0-9]{8}-[0-9]{2}$/";
		
		$_pattern = isset($patterns[$lotid]) ? $patterns[$lotid]:$patterns[0];
		
		if (preg_match($_pattern, $str))
			return $str;
		else
			return "";
	}
	
	function checksqlstr($getstr){
		$getstr = trim($getstr);
		//检测输入的参数是否含有sql敏感字符，如果有返回过滤后的符串
		if (strlen($getstr) == 0 || is_null($getstr)){
			$result="";
			return $result;
		}
		
		$pattern = "/法(\s|　)*轮(\s|　)*功|胡锦涛|共产党|基督教|毛席东|泽毛东|东毛席|席东毛|毛主席|席毛主|功法轮|轮法功|反日|日本主义者|台独|台湾独立|基督教|李登辉|自焚|江泽明|藏独|西藏独立|地震预测/i";
		$getstr = preg_replace($pattern, "", $getstr);
        $pattern = array(
                '/\biframe\b/i',
                '/\bjavascript\b/i',
                '/\bvbscript\b/i',
                '/\bscript\b/i',
                '/\bselect\b/i',
                '/\binsert\b/i',
                '/\bdelete\b/i',
                '/\bupdate\b/i',
                '/\bdrop\b/i',
                '/\bcreate\b/i',
                '/\bexec\b/i',
                '/\btruncate\b/i',
                '/\bdeclare\b/i'
        );
		$rep = array_fill(0,count($pattern),'');
		$getstr = preg_replace($pattern, $rep, $getstr);

        $s = array(chr(0), '0x', "'",  '<',    '>',    '   ',    "\r\n", "\n");
        $r = array('',     '',   "''", '&lt;', '&gt;', '&nbsp;', '<br>', '<br>');
        $getstr = str_replace($s, $r, $getstr);
		
		return $getstr;
	}

	function getpowervalue($adminname,$pageurl){
	//'获得用户对pageurl的权限值
	//'从数据库取出对应的权限值
	session_start();
	//$adminname=$_SESSION['adminname'];
	$result="";

	if ($adminname =="" or is_null($adminname)){
		header("Location:/b_manage/showerr.php?errmsg=错误：您没有登陆，或者您需要重新登陆&errtype=0");
	}
	if (isset($_SESSION['issuper']) && $_SESSION['issuper']==1){
		$result=255;
		return $result;
	}
	$dbh=Connect_r('conn_busi');
	
	$strsql = "BEGIN web_getuserpower (:username,:ac_url,:ac_value);END;";
	$stmt=ociparse($dbh,$strsql);
	
	ocibindbyname($stmt,":username",$adminname);
	ocibindbyname($stmt,":ac_url",$pageurl);
	ocibindbyname($stmt,":ac_value",$ac_value,3);
	ociexecute($stmt);
	$result=$ac_value;
	ocifreestatement($stmt);
	endconn($dbh);
	return $result;
	}

	function checkpower($userpower,$syspower){
      $userpower = cbyte($userpower);
      $syspower=cbyte($syspower);
      return $userpower . $syspower;
	}

	function jstop($strmsg){
	//'显示信息并回退一步
		$html = "<script>alert('" . $strmsg . "');if(history.length==0){window.opener='';window.close();}else{history.go(-1);}</script>";
		echo $html;
		exit();
	}
	function showmsgbox($strmsg,$strurl){	
		//显示信息
		$html = "<script>alert('" . $strmsg . "');window.location.href='".$strurl."'</script>";
		echo $html;
		exit();
	}
	function showmsgbox1($strmsg){
		//'显示信息
		$html = "<script>alert('" . $strmsg . "')</script>";
		echo $html;
	}
	function showcontent($strcontent)
	{
	  return preg_replace("/\r?\n/", "<br />", $strcontent);
	}

//'将字符串用指定的字符补齐到指定的长度
	//'fixstring------------需要补齐的字符串
	//'lens-----------------指定需要补齐的到的长度
	//'rightorleft----------左补齐还是右补齐
	//'tempstring-----------用来补齐的字符
	function formatfixuplen($fixstring,$lens,$rightorleft,$tempstring){
		$result=$fixstring;
		if (strlen($fixstring)==$lens){
			$result=$fixstring;
		}elseif (strlen($fixstring)>$lens){
			$result=substr($fixstring,($lens*(-1)));
		}else{
			if ($rightorleft="l"){
				//'fixstring="12"
				
				for ($i==1;$i<=($lens-strlen($fixstring));$i++){
					$result=$tempstring+$formatfixuplen;
				}
			}else{
				for ($i==1;$i<=($lens-strlen($fixstring));$i++){
					$result=$tempstring+$formatfixuplen;
				}
			}
		}
		return $result;
	}

	function checkstrisnum($str){
		$str2 = $str;
		$result="";
		while (strlen($str2)>0){
			$str1 = substr($str2,1);
			$str2 = substr($str2,(strlen($str2)-1)*(-1));
			if (!is_numeric($str1)){
				$result = false;
				return $result;
			}
		}
		$result = true;
		return $result;
	}
	
	function alertAndClosewin($msg,$isRefresh){
		//'功能：	弹出提示信息
		//'		刷新父窗口
		//'		关闭窗口
		//'参数：	msg 提示信息
		//'		isRefresh 是否刷新父窗口标志（1 刷新 0 不刷新）
			//endconn_busi();
			echo "<script language='javascript'>alert('$msg');</script>";
			if ($isRefresh=1){
				echo "<script language='javascript'>if(window.parent.dialogArguments!=null) window.parent.dialogArguments.document.execCommand('Refresh');</script>";
			}
			echo "<script language='javascript'>window.close();</script>";
			exit();
	}
	function jsRedirect($strurl){	
		//显示信息
		$html = "<script>window.location.href='".$strurl."';</script>";
		echo $html;
		exit();
	}
	//以下得到随机密码
	Function getRndCode($iCount){
		$strCode= "";
		$arrChar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ=+";
		$k=strlen($arrChar);
		For ($i=1;$i<$iCount;$i++){ 
		$j=intval(rand(1,$k))+1; 
		$strCode.= substr($arrChar,$j,1); 
		}
		return $strCode;
	}

    function getdomain(){
        $domain = strtolower(trim($_SERVER['SERVER_NAME']));
        return preg_match('/(500wan|boss|5000000)\..*/', $domain, $m) ? $m[0] : $domain;
    }

	//'返回状态信息（以XML的形式）
	function ReturnMessage($Mcode,$Messagestr,$Murl){
		//'=========如果Mcode 为 0，失败 ，1成功
		$strxml="<?xml version=\"1.0\" encoding=\"GB2312\"?>".chr(13).chr(10);
		$strxml.="<xml>".chr(13).chr(10);
		$strxml.="<code>".$Mcode."</code>".chr(13).chr(10);
		$strxml.="<msg><![CDATA[".$Messagestr."]]></msg>".chr(13).chr(10);
		$strxml.="<url><![CDATA[".$Murl."]]></url>".chr(13).chr(10);
		$strxml.="</xml>".chr(13).chr(10);
		echo $strxml;
		exit;
	}

    function getsortnamenew($orderid)
    {
    	switch ($orderid) {
        	case 0: // '没有定义
        		return "id";
        	case 1: // '发起时间
        		return "id";
        	case 2: // '人气指数
        		return "renqi";
        	case 3: // '方案金额
        		return "allmoney";
        	case 4: // '方案份数
        		return "anumber";
        	case 5: // '每份金额大小
        		return "onemoney";
        	case 6: // '方案点击率
        		return "clickstime";
        	case 7: // '战绩
        		return "zhanji";
        	default:
        		return "renqi";
    	}
    }
    //大底获得获得排序字段名 2008-10-28 wobby
    function GetDaDiSortName($orderid)
    {
    	switch ($orderid)
    	{
    		case 0: //没有定义
				return "id"; //按照发起时间
				break;
			case 1:   //发起时间
				return "id";
				break;
			case 2:	 //人气指数
				return "renqi";
				break;
			case 3:	 //方案金额
				return "allmoney";
				break;
			case 4: //方案份数
				return "anumber";
				break;
			case 5:	 //每份金额大小
				return "onemoney";
				break;
			case 6:	 //方案点击率
				return "clickstime";
				break;
			case 7: //战绩
				return "zhanji";
				break;
			default:
				return "renqi";
				break;
    	}
    }
    
 	function getRequest($sVar,$ret=null){
		if(isset($_REQUEST[$sVar]) && is_array($_REQUEST[$sVar]))
			return checkArrayValue($_REQUEST[$sVar]);
			
		return isset($_REQUEST[$sVar]) ? checksqlstr($_REQUEST[$sVar]) : $sRef;
	}
	function getPost($sVar,$sRef=NULL)
	{ 
		return isset($_POST[$sVar])?checksqlstr($_POST[$sVar]):$sRef;
	}   

	/**
	 * 检测身份证号码是否合法
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkIDCode( $str )
	{
		if( preg_match('/^[0-9a-zA-Z]{15,18}$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * 检测手机号码合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkMobile( $str )
	{
		if( preg_match('/^1\d{10}$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * 检测电话号码合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkPhone( $str )
	{
		if( preg_match('/^(?:0\d{2}-|0\d{3}-)?(?:\d{8}|\d{7})(?:-\d{1,5})?$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}

	/**
	 * 检测QQ号码合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkQQ( $str )
	{
		if( preg_match('/^(\d){5,12}$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}	
	
	/**
	 * 检测邮政编码合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkZipCode( $str )
	{
		if( preg_match('/^(\d){6}$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}		
	
	/**
	 * 检测电子邮件格式合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkEmail( $str )
	{
		if( preg_match('/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}		

	
	/**
	 * 检测生日合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkBirthDay( $str )
	{
		if( preg_match('/^(1|2)\d{3}\-(0|1)*\d-(0|1|2|3)*\d$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * 检测银行卡号合法性
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 */
	function checkBankCard( $str )
	{
		if( preg_match('/^\d{6,}$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}	

	/**
	 * 检测是否为 以,隔开的数字序列, 可以用来判断多选提交的
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @return bool
	 * 
	 */
	function checkMulBoxNum( $str )
	{
		if( preg_match('/^\d+(,\d+)*$/',$str) )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * 转化为金额格式
	 * @author wubingjie
	 * @param mixed $str	待检测字符串
	 * @param mixed $sep	货币符号
	 * @param mixed $f	小数个数
	 * @return $ret 金额格式的字符串
	 */
	function changeToMoney( $str, $sep="￥",$f=2 )
	{
		$f=(int)$f;
		$str = sprintf("%.".$f."f",$str);
		$arr = explode(".",$str);
		$ret = number_format($arr[0]);
		$ret = $sep.$ret;
		if( $f!=0 ){
			$ret = $ret.".".$arr[1];
		}
		return $ret;
	}
	
	/**
	 * 数据转化
	 * @author wubingjie
	 * @param mixed $str
	 * @param mixed $f
	 * @return $ret
	 */

	 function changeNum( $str, $f=2 )
	 {
	 	$f=(int)$f;
		$ret = sprintf("%.".$f."f",$str);
		if($ret>floatval($str)){
			$_tem = 1;
			for($i=0;$i<$f;$i++){
				$_tem /= 10;
			}
			$ret -= floatval($_tem);
		}
		return $ret;
	 }

	/**
	 * 时间比较函数，返回两个日期相差几秒、几分钟、几小时或几天
	 * @author wubingjie
	 * @param mixed $date1	
	 * @param mixed $date2	
	 * @param mixed $unit	
	 * @return string|bool
	 */
	function dateDiff($date1, $date2, $unit = "") 
	{ 
		switch ($unit) 
		{
		   case 's':
		    $dividend = 1;
		    break;
		   case 'i':
		    $dividend = 60;
		    break;
		   case 'h':
		    $dividend = 3600;
		    break;
		   case 'd':
		    $dividend = 86400;
		    break;
		   default:
		    $dividend = 86400;
		}
		$time1 = strtotime($date1);
		$time2 = strtotime($date2);
		if ($time1 && $time2)
		{
		   return (float)($time1 - $time2) / $dividend;
		}
		return false;
	}	
	
	/**
	 * 获取IP 
	 * 
	 * @author wubingjie
	 * @return 真实IP地址
	 */
	function getIP() 
	{
	    if ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ) {
	        return $_SERVER["HTTP_X_FORWARDED_FOR"]; 
	    } elseif ( isset($_SERVER["HTTP_X_REAL_IP"]) ) {
            return $_SERVER["HTTP_X_REAL_IP"];
        }
	    return $_SERVER["REMOTE_ADDR"]; 
	} 

	/**
	 * IP转换为Long
	 * 
	 * @author wubingjie
	 * @param string $ip
	 * @return 转换完的ip
	 */
	function ipToLong( $ip )
	{
		$iptolong = 0;
		if(trim($ip)=='')
		{
			$iptolong = 0;
		}
		
		$arr = explode( '.', $ip );
		if( count($arr)<4 )
		{
			$iptolong = 0;
		}
		else 
		{
			$iptolong = 256*256*256*intval($arr[0])+256*256*intval($arr[1])+256*intval($arr[2])+intval($arr[3]);
		}
		return $iptolong;
	}
	
	
	/**
	 * 编码转换
	 * @author wubingjie
	 * @param int $str
	 * @return string 返回指定的字符
	 */
	function code2utf($num)
	{
	  if($num<128)return chr($num);
	  if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
	  if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
	  if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
	  return '';
	}	
	
	/**
	 * 解释JS escape 字符串
	 * @author wubingjie
	 * @param string $str
	 * @return string unescape字符串
	 */
	function unescape( $str ) 
	{
		$decodedStr = '';
		$pos = 0;
		$len = strlen ($str);
		while ($pos < $len) 
		{
			$charAt = substr ($str, $pos, 1);
			if ($charAt == '%')
			{
				$pos++;
				$charAt = substr ($str, $pos, 1);
				if ($charAt == 'u') 
				{
					//unicode character
					$pos++;
					$unicodeHexVal = substr ($str, $pos, 4);
					$unicode = hexdec ($unicodeHexVal);
					$decodedStr .= iconv("UTF-8", 'gb18030', code2utf($unicode));
					$pos += 4;
				}
				else 
				{
					//escaped ascii character
					$hexVal = substr ($str, $pos, 2);
					$decodedStr .= chr (hexdec ($hexVal));
					$pos += 2;
				}
			}
			else 
			{
				$decodedStr .= $charAt;
				$pos++;
			}
		}
		
		return $decodedStr;
	}

		
	/**
	 * 小数部分第三位进1,小数部分结果为两位
	 * @author wubingjie
	 *
	 */
	function formatNum( $num )
	{
		if( preg_match('/(\d+)\.((?:\d){2})(\d+)/',strval($num),$arr))
		{
			if( floatval("0.00".$arr[3] )>0 )
			{
				$num = floatval($arr[1].".".$arr[2])+0.01;
			}
		}

		return sprintf("%0.2f",floatval($num));

	}
	

	/** 
         * 转换为安全输入参数
         * @author wubingjie
         * @param string $str 字符串
	 * @return string 安全的参数
         */
	function tranInject( $str ) 
	{
		$ret = '';
        	if( isset( $str ) && strlen( $str )>0 ){
			
			//转义单引号、双引号、反斜线、NULL
        	       	if (!get_magic_quotes_gpc()){
				$str = addslashes($str);
			}
	
			//敏感字符列表
			$arrPatterns = array('/\bupdate\b/','/\bdelete\b/',
			'/\bselect\b/','/\binsert\b/','/\bdrop\b/','/\bcreate\b/',
			'/\bexec\b/','/法[ 　]*轮[ 　]*功|台独|台湾独立|藏独|西藏独立|地震预测/',
			'/\-\-/','/#/','/\/\*/','/%/','/_/');
			
			//转化为安全字符
			$arrReplaces = array('ｕｐｄａｔｅ','ｄｅｌｅｔｅ','ｓｅｌｅｃｔ',
			'ｉｎｓｅｒｔ','ｄｒｏｐ','ｃｒｅａｔｅ','ｅｘｅｃ','','－－','＃',
			'／＊','％','—');

			//

			$ret = preg_replace($arrPatterns, $arrReplaces, $str);
		}
		
		return $ret;
	}
	/**
	 * 纪录cookies
	 * @author wujian
	 * @param string $ck_id	检测标识码
	 * @param string $user	用户名
	 * @param string $tmppass	用户临时密码
	 * @param string $web_type	用户站点类型
	 * @param string $remote_host	访问者ip
	 */
	function set_LoginCookie($ck_id,$user,$tmppass,$web_type,$remote_host,$lasttime=""){
		$domain=""; 
		$domain = getdomain();
		if ($lasttime == "") $lasttime = date("Y-m-d H:i:s");
		setcookie("500wan%5Fusername",base64_encode($user),null,'/',$domain);	//用户名
		setcookie("500wan%5Fuserps",base64_encode(md5($tmppass)),null,'/',$domain);	//用户临时密码
		setcookie("usercheck",$ck_id,null,'/',$domain);	//检测码
		setcookie("ul",$web_type."1",null,'/',$domain);		//站点标识
		setcookie("500wanuser",base64_encode($user),null,'/',$domain);	//用户名
		setcookie("500wan%5FlastTime",$lasttime,null,'/',$domain);	//用户登录时间
		setcookie("500wan%5FlastIP",$remote_host,null,'/',$domain);		//用户登录IP
	}

	function OFile($url,$postfield,$referer=""){
	 		if ($referer=="")$referer=$url;
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
			curl_setopt($ch, CURLOPT_POST, 1);//启用POST提交
    			curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield); //设置POST提交的字符串
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
			curl_setopt($ch,CURLOPT_TIMEOUT,120);
			curl_setopt($ch,CURLOPT_REFERER,$referer);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
			$content=curl_exec($ch);
			$info=curl_getinfo($ch);
			curl_close($ch);
			return $content;
	}
	
	/**
	 * 输入ID，获得发卡银行名称
	 * @author 钟远华
	 * @param string $type	银行类型ID
	 * @return string 发卡银行名称
	 */
	function GetBankNameById($type) {
		if($type=="0") {
			return "招商银行";
		} elseif ($type=="2") {
			return "工商银行";
		} elseif ($type=="3") {
			return "建设银行";
		} else {
			return "其它";
		}
	}
	
	/**
	 * 输入ID，获得银行卡发卡地区
	 * @author 钟远华
	 * @param string $type	银行类型ID
	 * @return string 银行卡发卡地区
	 */
	function GetBankZoneById($type) {
		if($type=="0") {
			return "深圳本地";
		} else {
			return "其它";
		}
	}
	
	/**
	 * 页面去缓存
	 * @author 钟远华
	 */
	function noCache() {
		header('Expires: Thu, 01 Jan 1970 00:00:01 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-cache, must-revalidate, max-age=0');
		header('Pragma: no-cache');
	}
	/**
	 * 域名检测
	 * @author zhongyuanhua
	 * @param string $url
	 * @return string 传入网址，如果域名不允许，返回空字符串，否则返回原网址
	 */
    function checkUrl($url) {
    	//控制传入地址的域名
    	$strUrl = $url;
		ereg('http://[^.]*\.[^.]+\.[^/]+', $url, $r);
		$arr_domain_allow = array(
			"",
			"http://www.500wan.com",
			"http://news.500wan.com",
			"http://trade.500wan.com",
			"http://trade2.500wan.com",
			"http://passport.500wan.com",
			"http://passport2.500wan.com",
			"http://speed.500wan.com",
			"http://trade.boss.com",
			"http://ntrade.boss.com",
			"http://ntrade2.boss.com",
			"http://passport.boss.com",
			"http://speed.boss.com",
			"http://game.boss.com",
			"http://game.500wan.com"
			);
		if(!in_array($r[0],$arr_domain_allow)) {
			$strUrl = "";
		}
		return $strUrl;
    }
	
	 /**
     * 检测日期合法性
     *
     * @param string $adate 日期
     * @return True/False
     */
    function isValidDate($adate){
		$validDate = explode("-",$adate);
		return is_array($validDate) && isset($validDate['0']) && isset($validDate['1']) && isset($validDate['2']) && checkdate($validDate['1'],$validDate['2'],$validDate['0']);
    }
    
    /****函数功能：判断密码的强弱
	* @author wuchupeng
	关联函数corpsesPwd($password)
	说明  返回值  规则
	很弱  1  	少于6位数的任何组合
	弱    2		6-8位数以内的纯数字或字母（纯大写或纯小写）
	中    3		超过8-11位数的纯数字或字母（纯大写或纯小写） / 超过6-9位数的任意两种混搭（数字/大写/小写/符号）
	强    4		超过11位数的纯数字或字母（纯大写或纯小写） / 超过9位数的任意两种混搭（数字/大写/小写/符号）
	很强  5		超过10位数的任意三种混搭（数字/大写/小写/符号）
	*/
	//检查密码等级
	function checkPwdLevel ($password)
	{
		//密码为空，返回flase
		if (!$password) return 0; //未开通密码保护
		//判断密码中是否有数字
		$maths = preg_match("/([0-9]+)/", $password);
		//判断密码中是否有大写
		$bigs = preg_match("/([A-Z]+)/", $password);
		//判断密码中是否有小写
		$smalls = preg_match("/([a-z]+)/", $password);
		//判断密码中是否有特殊字符
		$corps = corpsesPwd ($password);
		//计算密码中有多少种组合
		$num = $maths + $smalls + $bigs + $corps;
		//获取密码长度
		$pwdLeng = strlen($password);
		//很弱  	少于6位数的任何组合
		if($pwdLeng<6) return 1;

		if($pwdLeng >=6 && $pwdLeng <=8)
		{
	        if($num == 1)return  1;
		    if($num == 2 || $num == 3)return  2;
		    if($num == 4)return  3;
		}

		if($pwdLeng >8 && $pwdLeng <= 11)
		{
	        if($num ==1) return  2;
			if($num == 2) return  3;
			if($num == 3) return  4;
			if($num == 4) return  5;
		}

		if($pwdLeng > 11)
		{
		    if($num ==1) return  3;
			if($num ==2) return  4;
			if($num >2) return  5;
		}
  	}


	//判断密码是否有特殊字符
	//* @author wuchupeng
	/*function corpsesPwd ($password)
	{
		$pwdLeng = strlen($password);
		for($i=0;$i<$pwdLeng;$i++)
		{
			$pwdStr = substr($password,$i,1);
			$maths = preg_match("/([0-9]+)/", $pwdStr);
			$bigs = preg_match("/([A-Z]+)/", $pwdStr);
			$smalls = preg_match("/([a-z]+)/", $pwdStr);
			if(!$maths && !$smalls && !$bigs){return  1;}
		}
		return 0;
	}*/

	//rewrite by yeqh 2010-5-17
	function corpsesPwd($password){
		return !preg_match('/^[A-Za-z0-9]+$/',$password);
	}
	//chenjie 清楚所有cookie
	function clearAllCookie(){
		setcookie("500wanregfrom",'',null,"/",getdomain(),null);
		setcookie("500wanregchanel",'',null,"/",getdomain(),null);
		setcookie("500wanRegFromUrl",'',null,"/",getdomain(),null);
		setcookie("500wanRegUrl",'',null,"/",getdomain(),null);
		setcookie("500wanNextfrom",'',null,"/",getdomain(),null);
	}
	
	//用户是否可以修改真实姓名、身份证、银行卡类型 by yeqh 2010-5-26
	function canModTnameIdnoCard($username){
		$userInfo = User_User::getUserExpInfo($username);
		if($userInfo){
			if($userInfo[0]['UI_CAROFBANK']==6 || $userInfo[0]['UI_CAROFBANK']==10){//财付通&&支付宝
				return false;
			}else{
				return true;
			}
		}else{
			return true;
		}
	}
	function getmicrotime()    
	{    
		list($usec, $sec) = explode(" ",microtime());    
		return ((float)$usec + (float)$sec);    
	} 
 